package com.atlige.gzmall.product.exception;

import com.atlige.common.exception.GzmallCodeEnum;
import com.atlige.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 * @author Jeremy Li
 * @data 2021/3/19 - 23:25
 */
@Slf4j
//@RestControllerAdvice(basePackages = "com.atlige.gzmall.product.controller")
public class GzmallException {
    /**
     * 处理数据校验的异常
     * @param e
     * @return
     */
    //@ExceptionHandler(value = Exception.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题：{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            String field = item.getField();
            String message = item.getDefaultMessage();
            errorMap.put(field, message);
        });
        return R.error(GzmallCodeEnum.VALID_EXCEPTION.getCode(), GzmallCodeEnum.VALID_EXCEPTION.getMessage()).put("data", errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        return R.error(GzmallCodeEnum.UNKNOW_EXCEPTION.getCode(), GzmallCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }


}
